package com.econ.powercloud.ems.service.biz;

import com.econ.powercloud.common.base.facade.enums.StatusType;
import com.econ.powercloud.common.base.facade.exception.CommonRuntimeException;
import com.econ.powercloud.common.base.facade.util.JacksonUtil;
import com.econ.powercloud.ems.common.enums.SvgRelationType;
import com.econ.powercloud.ems.dal.entity.EmsEnergyStation;
import com.econ.powercloud.ems.dal.entity.SystemSvg;
import com.econ.powercloud.ems.pojo.SystemSvgVO;
import com.econ.powercloud.ems.pojo.requestVO.FileRequestVO;
import com.econ.powercloud.ems.pojo.requestVO.SystemSvgRequestVO;
import com.econ.powercloud.ems.service.dao.EmsEnergyStationDAO;
import com.econ.powercloud.ems.service.dao.SystemSvgDAO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author jwc
 * @date 2023/05/08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemSvgBizService {
    private final SystemSvgDAO systemSvgDAO;
    private final EmsEnergyStationDAO emsEnergyStationDAO;

    /**
     * 新增/修改svg
     * @param requestVO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SystemSvgRequestVO requestVO) {
        String stationId = this.getStationId();
        SystemSvg systemSvg = systemSvgDAO.getById(requestVO.getId());
        if(systemSvg == null){
            SystemSvg insertSvg = JacksonUtil.convertToObj(requestVO, SystemSvg.class);
            insertSvg.setRelationId(stationId);
            insertSvg.setGmtCreate(System.currentTimeMillis());
            insertSvg.setGmtModify(System.currentTimeMillis());
            systemSvgDAO.save(insertSvg);
        }else {
            systemSvg = JacksonUtil.convertToObj(requestVO, SystemSvg.class);
            systemSvg.setRelationId(systemSvg.getRelationId());
            systemSvg.setGmtModify(System.currentTimeMillis());
            systemSvgDAO.updateById(systemSvg);
        }
        return true;
    }

    /**
     * 删除svg
     * @param id svg主键id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer id) {
        systemSvgDAO.removeById(id);
        return true;
    }

    /**
     * 获取svg详情
     * @param id svg主键id
     * @return
     */
    public SystemSvgVO getSvg(Integer id) {
        SystemSvg svg = systemSvgDAO.getById(id);
        Assert.notNull(svg, "svg不存在");
        SystemSvgVO svgVO = JacksonUtil.convertToObj(svg, SystemSvgVO.class);
        return svgVO;
    }

    /**
     * 获取子svg
     * @param parentId 父svg的id
     * @return
     */
    public List<SystemSvgVO> getChildSvg(Integer parentId) {
        List<SystemSvg> systemSvgs = systemSvgDAO.selectByParentId(parentId);
        List<SystemSvgVO> systemSvgVOList = JacksonUtil.convertToList(systemSvgs, SystemSvgVO.class);
        return systemSvgVOList;
    }

    /**
     * 获取关联id与关联类型下的所有svg
     * @param relationId
     * @param relationType
     * @return
     */
    public List<SystemSvgVO> getSvgListByCondition(String relationId,String relationType,Integer type,String tag) {
        List<SystemSvg> systemSvgs = systemSvgDAO.selectListByCondition(relationId, relationType,type,tag);
        if(CollectionUtils.isEmpty(systemSvgs)){
            return Collections.emptyList();
        }
        List<SystemSvgVO> systemSvgVOList = JacksonUtil.convertToList(systemSvgs, SystemSvgVO.class);
        //这里为了减少返回前端的数据大小,把source赋空
        systemSvgVOList.stream().forEach(d-> d.setSource(null));
        return systemSvgVOList;
    }

    /**
     * 删除svg
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(String relationId,String relationType) {
        systemSvgDAO.deleteByRelationIdAndRelationType(relationId,relationType);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean batchImportSvg(FileRequestVO fileRequestVO){
        List<EmsEnergyStation> stationList = emsEnergyStationDAO.list();
        if(CollectionUtils.isEmpty(stationList)){
            throw new CommonRuntimeException(StatusType.FAIL,"未配置储能站！");
        }
        EmsEnergyStation station = stationList.get(0);
        String stationId = station.getEnergyStationId();
        String svgJson = this.getFileContent(fileRequestVO.getFile());
        if(StringUtils.isEmpty(svgJson)){
            throw new CommonRuntimeException(StatusType.FAIL,"文件内容为空");
        }
        List<SystemSvgRequestVO> systemSvgList = JacksonUtil.parseList(svgJson,SystemSvgRequestVO.class);
        String relationId = stationId;
        String relationType = SvgRelationType.STATION_ID.getCode();
        systemSvgDAO.deleteByRelationIdAndRelationType(relationId,relationType);
        List<SystemSvg> insertList = JacksonUtil.convertToList(systemSvgList,SystemSvg.class);
        insertList.stream().forEach(d->{
            d.setRelationId(stationId);
            d.setRelationType(relationType);
            d.setGmtCreate(System.currentTimeMillis());
            d.setGmtModify(System.currentTimeMillis());
        });
        systemSvgDAO.saveBatch(insertList);
        //更新储能站的svg图的最新时间字段
        station.setSvgGmtModify(System.currentTimeMillis());
        emsEnergyStationDAO.updateById(station);
        return true;
    }

    private String getFileContent(MultipartFile file){
        StringBuilder stringBuilder = new StringBuilder();
        InputStream inputStream = null;
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        try {
            inputStream = file.getInputStream();
            streamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(streamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        }catch (Exception e){
            throw new CommonRuntimeException(StatusType.FAIL,"读取文件失败！");
        }finally {
            try {
                if(reader != null){
                    reader.close();
                }
                if(streamReader != null){
                    streamReader.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (Exception e){

            }
        }
    }

    private String getStationId(){
        List<EmsEnergyStation> stationList = emsEnergyStationDAO.list();
        if(CollectionUtils.isEmpty(stationList)){
            throw new CommonRuntimeException(StatusType.FAIL,"未配置储能站！");
        }
        return stationList.get(0).getEnergyStationId();
    }

}
